import core.constants
import core.yt_helper
import core.globals

import gdata
import gdata.youtube.service
import random

class Authenticator:

	def __init__(self,email,password):
		self.email = email
		self.password = password

	def create_authenticated_yt_service(self):
		yt_service = gdata.youtube.service.YouTubeService()
		
		yt_service.developer_key = constants.DEVELOPER_KEY
		yt_service.client_id = constants.APPLICATION_NAME
		yt_service.source = constants.APPLICATION_NAME
		
		yt_service.email = self.email
		yt_service.password = self.password
		
		try:
			yt_service.ProgrammaticLogin()
		except gdata.service.BadAuthentication:
			globals.exception_handler.handle_expected_fatal_exception('auth.wrong_credentials',(yt_service.email))
		except gdata.service.CaptchaRequired:
			globals.exception_handler.handle_expected_fatal_exception('auth.captcha_required')
		return yt_service
		
class PlaylistManager:
	
	def __init__(self,yt_service,playlist_name):
		self.yt_service = yt_service
		
		playlist_id,playlist_video_feed = self._load_playlist(playlist_name)
		print playlist_video_feed
		self.playlist_uri = 'http://gdata.youtube.com/feeds/api/playlists/%s' % (playlist_id)
		self.videos = yt_helper.obtain_merged_feed_entries(playlist_video_feed,self.yt_service,gdata.youtube.YouTubePlaylistVideoFeedFromString)
		
	def _load_playlist(self,playlist_name):
		playlist_feed = self.yt_service.GetYouTubePlaylistFeed()
		playlist_entries = yt_helper.obtain_merged_feed_entries(playlist_feed,self.yt_service,gdata.youtube.YouTubePlaylistFeedFromString)
		
		for entry in playlist_entries:
			if entry.title.text.lower() == playlist_name.lower():
				id = yt_helper.get_id_for_feed_entry(entry)
				return id,self.yt_service.GetYouTubePlaylistVideoFeed(playlist_id=id)
		
		globals.exception_handler.handle_expected_fatal_exception('playlist_not_found',(playlist_name))
		
	def get_videos(self):
		return self.videos
		
	def move_track_to_position(self,track_id,position):
		try:
			self.yt_service.UpdatePlaylistVideoEntryMetaData(self.playlist_uri, track_id,None,None,position)
		except gdata.service.RequestError as e:
			if e[0]['status'] == 500:
				#Bug in gdata. Internal server error is thrown but track position is actually changed. So we choke the exception.
				pass
			else:
				raise
		
if __name__ == "__main__":
	authenticator = Authenticator('IAmPeteRockFan','ownage77')
	yt_service = authenticator.create_authenticated_yt_service()
	mgr = PlaylistManager(yt_service,"90's favourites")
	videos = mgr.get_videos()
	#print videos[27].title.text